from django.shortcuts import render, redirect
from workDjango import models
from workDjango.models import Product, CategorySummary, BrandSummary, RatingGroupSummary, ProductSales, StoreSummary
from workDjango.utils import BootStrapModelForm
from django.dispatch import receiver
from django.db.models.signals import post_save, post_delete


# 数据表判断

# 数据展示1--所有商品数据展示
def goods_show(request):
    table_choice = request.GET.get('table_choice')
    print(table_choice)
    if table_choice == "sales":
        goods_sales = models.ProductSales.objects.all()
        return render(request, 'goods_show.html',
                      {"items": goods_sales, "active_page": 'data_show', "table_choice": table_choice})
    elif table_choice == "category":
        goods_categories = models.CategorySummary.objects.all()
        return render(request, 'goods_show.html',
                      {"items": goods_categories, "active_page": 'data_show', "table_choice": table_choice})
    elif table_choice == "brand":
        goods_brands = models.BrandSummary.objects.all()
        return render(request, 'goods_show.html',
                      {"items": goods_brands, "active_page": 'data_show', "table_choice": table_choice})
    elif table_choice == "store":
        goods_store = models.StoreSummary.objects.all()
        return render(request, 'goods_show.html',
                      {"items": goods_store, "active_page": 'data_show', "table_choice": table_choice})
    else:
        table_choice = "product"
        params = {
            'product_id': request.GET.get('product_id', ''),
            'category': request.GET.get('category', ''),
            'brand': request.GET.get('brand', ''),
            'name': request.GET.get('name', '')
        }

        # 过滤掉空值
        filtered_params = {k: v for k, v in params.items() if v}

        # 构建查询条件
        queryset = Product.objects.all()
        if 'product_id' in filtered_params:
            queryset = queryset.filter(product_id=filtered_params['product_id'])
        if 'category' in filtered_params:
            queryset = queryset.filter(category=filtered_params['category'])
        if 'brand' in filtered_params:
            queryset = queryset.filter(brand=filtered_params['brand'])
        if 'name' in filtered_params:
            queryset = queryset.filter(product_name=filtered_params['name'])
        print(table_choice)
        return render(request, 'goods_show.html',
                      {'items': queryset, "active_page": 'data_show', "table_choice": table_choice})


# 数据修改

# 定义信号处理函数

# @receiver(post_save, sender=Product)
# def update_product_counts_on_save(sender, instance, created, **kwargs):
#     if created:
#         # 新增产品时，增加 CategorySummary 和 BrandSummary 的 num_products
#         instance.category.num_products += 1
#         instance.category.total_sales += 1
#         instance.category.save()
#         instance.brand.num_products += 1
#         instance.brand.total_sales += 1
#         instance.brand.save()
#         ProductSales.objects.create(product=instance, quantity=1)
#     else:
#         # 更新产品时，不需要额外操作 CategorySummary 和 BrandSummary 的 num_products
#         pass
#
#
# @receiver(post_delete, sender=Product)
# def update_product_counts_on_delete(sender, instance, **kwargs):
#     # 删除产品时，减少 CategorySummary 和 BrandSummary 的 num_products
#     instance.category.num_products -= 1
#    # instance.category.total_sales -= 1
#     instance.category.save()
#     instance.brand.num_products -= 1
#    # instance.brand.total_sales -= 1
#     instance.brand.save()
#     ProductSales.objects.filter(product=instance).delete()
#
#
# @receiver(post_save, sender=ProductSales)
# def update_sales_detail_on_save(sender, instance, created, **kwargs):
#     if created:
#         # 新增销售记录时，增加 CategorySummary 和 BrandSummary 的 total_sales
#         pass
#     else:
#         # 更新销售记录时，更新 CategorySummary 和 BrandSummary 的 total_sales
#         # 计算销售记录的差值
#         old_quantity = ProductSales.objects.get(pk=instance.pk).quantity
#         quantity_change = instance.quantity - old_quantity
#
#         # 更新 CategorySummary 和 BrandSummary 的 total_sales
#         CategorySummary.objects.filter(id=instance.product.category.id).update(
#             total_sales=instance.product.category.total_sales + quantity_change)
#         BrandSummary.objects.filter(id=instance.product.brand.id).update(
#             total_sales=instance.product.brand.total_sales + quantity_change)
#         # instance.category.total_sales += quantity_change
#         # instance.category.save()
#         # instance.brand.total_sales += quantity_change
#         # instance.brand.save()
#
#
# @receiver(post_delete, sender=ProductSales)
# def update_sales_detail_on_delete(sender, instance, **kwargs):
#     # 删除销售记录时，减少 CategorySummary 和 BrandSummary 的 total_sales
#     CategorySummary.objects.filter(id=instance.product.category.id).update(
#         total_sales=instance.product.category.total_sales - instance.quantity)
#     BrandSummary.objects.filter(id=instance.product.brand.id).update(
#         total_sales=instance.product.brand.total_sales - instance.quantity)
#
#     # instance.category.total_sales -= instance.quantity
#     # instance.category.save()
#     # instance.brand.total_sales -= instance.quantity
#     # instance.brand.save()


# class EditModelForm(BootStrapModelForm.EditModelForm):
#     class Meta:
#         model = models.Product
#         fields = ["product_id", "category", "brand", "name"]

# 数据更改
# def goods_update(request, table_name, id_name, id, ModelForm):
#     data = table_name.objects.filter(id_name=id).first()
#     if request.method == "GET":
#         form = ModelForm(instance=data)
#         return render(request, "good_update.html", {"edit_form": form})
#     form = ModelForm(data=request.POST, instance=data)
#     if form.is_valid():
#         form.save()
#         return redirect('/system/data_show')
#     return render(request, 'good_update.html', {"edit_form": form})
#

def goods_update(request, table_choice, id):
    if table_choice == "product":
        class ProductEditModelForm(BootStrapModelForm.EditModelForm):
            class Meta:
                model = models.Product
                fields = ["product_id", "product_name", "price", "category", "sales_volume", "brand", "rating", "store"]

        data = Product.objects.filter(product_id=id).first()
        if request.method == "GET":
            form = ProductEditModelForm(instance=data)
            return render(request, "good_update.html", {"edit_form": form})
        form = ProductEditModelForm(data=request.POST, instance=data)
        if form.is_valid():
            form.save()
            return redirect('/system/data_show')
        return render(request, 'good_update.html', {"edit_form": form})
    elif table_choice == "sales":
        class SalesEditModelForm(BootStrapModelForm.EditModelForm):
            class Meta:
                model = models.ProductSales
                fields = ["product_id", "product_name", "sales_volume", "category", "brand", "rating", "store"]

        data = ProductSales.objects.filter(product_id=id).first()
        if request.method == "GET":
            form = SalesEditModelForm(instance=data)
            return render(request, "good_update.html", {"edit_form": form})
        form = SalesEditModelForm(data=request.POST, instance=data)
        if form.is_valid():
            form.save()
            return redirect(f'/system/data_show')
        return render(request, 'good_update.html', {"edit_form": form})
    elif table_choice == "category":
        class CategorySummaryEditModelForm(BootStrapModelForm.EditModelForm):
            class Meta:
                model = models.CategorySummary
                fields = ["category", "total_sales_volume", "avg_rating", "avg_price", "avg_sales_volume_per_product",
                          "max_price", "min_price"]

        data = CategorySummary.objects.filter(category=id).first()
        if request.method == "GET":
            form = CategorySummaryEditModelForm(instance=data)
            return render(request, "good_update.html", {"edit_form": form})
        form = CategorySummaryEditModelForm(data=request.POST, instance=data)
        if form.is_valid():
            form.save()
            return redirect('/system/data_show')
        return render(request, 'good_update.html', {"edit_form": form})
    elif table_choice == "brand":
        class BrandSummaryEditModelForm(BootStrapModelForm.EditModelForm):
            class Meta:
                model = models.BrandSummary
                fields = ["brand", "total_sales_volume", "avg_rating", "avg_price", "avg_sales_volume_per_product",
                          "max_price", "min_price"]

        data = BrandSummary.objects.filter(brand=id).first()
        if request.method == "GET":
            form = BrandSummaryEditModelForm(instance=data)
            return render(request, "good_update.html", {"edit_form": form})
        form = BrandSummaryEditModelForm(data=request.POST, instance=data)
        if form.is_valid():
            form.save()
            return redirect('/system/data_show')
        return render(request, 'good_update.html', {"edit_form": form})
    elif table_choice == "customer_review":
        class RatingGroupSummaryEditModelForm(BootStrapModelForm.EditModelForm):
            class Meta:
                model = models.RatingGroupSummary
                fields = ["rating_group", "total_sales_volume", "avg_rating", "avg_price",
                          "avg_sales_volume_per_product", "max_price", "min_price"]

        data = RatingGroupSummary.objects.filter(review_id=id).first()
        if request.method == "GET":
            form = RatingGroupSummaryEditModelForm(instance=data)
            return render(request, "good_update.html", {"edit_form": form})
        form = RatingGroupSummaryEditModelForm(data=request.POST, instance=data)
        if form.is_valid():
            form.save()
            return redirect('/system/data_show')
        return render(request, 'good_update.html', {"edit_form": form})
    else:
        class StoreSummaryEditModelForm(BootStrapModelForm.EditModelForm):
            class Meta:
                model = models.StoreSummary
                fields = ["store", "total_sales_volume", "avg_rating", "avg_price", "avg_sales_volume_per_product",
                          "max_price", "min_price"]

        data = StoreSummary.objects.filter(store=id).first()
        if request.method == "GET":
            form = StoreSummaryEditModelForm(instance=data)
            return render(request, "good_update.html", {"edit_form": form})
        form = StoreSummaryEditModelForm(data=request.POST, instance=data)
        if form.is_valid():
            form.save()
            return redirect('/system/data_show')
        return render(request, 'good_update.html', {"edit_form": form})


# 数据删除
def goods_delete(request, table_choice, id):
    if table_choice == "product":
        models.Product.objects.filter(product_id=id).delete()
    # models.ProductSales.objects.filter(product_id=id).delete()
    # models.RatingGroupSummary.objects.filter(product_id=id).delete()
    elif table_choice == "sales":
        models.ProductSales.objects.filter(product_id=id).delete()
    elif table_choice == "category":
        models.CategorySummary.objects.filter(category=id).delete()
    elif table_choice == "brand":
        models.BrandSummary.objects.filter(brand=id).delete()
        # models.Product.objects.filter(brand_id=id).delete()
    elif table_choice == "store":
        models.StoreSummary.objects.filter(store=id).delete()
        # models.Product.objects.filter(review_id=id).delete()
    # Product.objects.filter(product_id=id).delete()
    return redirect('/system/data_show')


# 数据添加
# class AddModelForm(BootStrapModelForm.AddModelForm):
#     class Meta:
#         model = models.Product
#         fields = ["product_id", "category", "brand", "name", "price"]


def goods_add_choice(request):
    if request.method == "GET":
        return render(request, "goods_add.html")


def goods_add(request):
    table_choice = request.GET.get("table_choice")
    if table_choice == "sales":
        class SalesAddModelForm(BootStrapModelForm.AddModelForm):
            class Meta:
                model = models.ProductSales
                fields = ["product_id", "product_name", "sales_volume", "category", "rating", "store"]
                # fields = ["sale_id", "product", "quantity", "cumulative_quantity"]

        if request.method == "GET":
            form = SalesAddModelForm()
            return render(request, 'goods_add.html', {"add_form": form})
        form = SalesAddModelForm(data=request.POST)
        if form.is_valid():
            form.save()
            return redirect('/system/data_show')
        return render(request, 'goods_add.html', {"add_form": form})
    elif table_choice == "category":
        class CategorySummaryAddModelForm(BootStrapModelForm.AddModelForm):
            class Meta:
                model = models.CategorySummary
                fields = ["category", "total_sales_volume", "avg_rating", "avg_price", "avg_sales_volume_per_product",
                          "max_price", "min_price"]

        if request.method == "GET":
            form = CategorySummaryAddModelForm()
            return render(request, 'goods_add.html', {"add_form": form})
        form = CategorySummaryAddModelForm(data=request.POST)
        if form.is_valid():
            form.save()
            return redirect('/system/data_show')
        return render(request, 'goods_add.html', {"add_form": form})
    elif table_choice == "brand":
        class BrandSummaryAddModelForm(BootStrapModelForm.AddModelForm):
            class Meta:
                model = models.BrandSummary
                fields = ["brand", "total_sales_volume", "avg_rating", "avg_price", "avg_sales_volume_per_product",
                          "max_price", "min_price"]

        if request.method == "GET":
            form = BrandSummaryAddModelForm()
            return render(request, 'goods_add.html', {"add_form": form})
        form = BrandSummaryAddModelForm(data=request.POST)
        if form.is_valid():
            form.save()
            return redirect('/system/data_show')
        return render(request, 'goods_add.html', {"add_form": form})
    elif table_choice == "customer_review":
        class RatingGroupSummaryAddModelForm(BootStrapModelForm.AddModelForm):
            class Meta:
                model = models.RatingGroupSummary
                fields = ["rating_group", "total_sales_volume", "avg_rating", "avg_price",
                          "avg_sales_volume_per_product", "max_price", "min_price"]

        if request.method == "GET":
            form = RatingGroupSummaryAddModelForm()
            return render(request, 'goods_add.html', {"add_form": form})
        form = RatingGroupSummaryAddModelForm(data=request.POST)
        if form.is_valid():
            form.save()
            return redirect('/system/data_show')
        return render(request, 'goods_add.html', {"add_form": form})
    else:
        class ProductAddModelForm(BootStrapModelForm.AddModelForm):
            class Meta:
                model = models.Product
                fields = ["product_id", "product_name", "price", "category", "sales_volume", "brand", "rating", "store"]

        if request.method == "GET":
            form = ProductAddModelForm()
            return render(request, 'goods_add.html', {"add_form": form})
        form = ProductAddModelForm(data=request.POST)
        if form.is_valid():
            form.save()
            return redirect('/system/data_show')
        return render(request, "goods_add.html", {"add_form", form})


# 2.销售详情数据展示
def goods_sales_show(request):
    table_choice = request.GET.get('table_choice')
    goods_sales = models.ProductSales.objects.all()
    return render(request, 'goods_show.html',
                  {"items": goods_sales, "active_page": 'data_show', "table_choice": table_choice})


# 3.商品分类表展示
def goods_category_show(request):
    table_choice = request.GET.get('table_choice')
    goods_categories = models.CategorySummary.objects.all()
    return render(request, 'goods_show.html',
                  {"items": goods_categories, "active_page": 'data_show', "table_choice": table_choice})


# 商品品牌表展示
def goods_brand_show(request):
    table_choice = request.GET.get('table_choice')
    goods_brands = models.BrandSummary.objects.all()
    return render(request, 'goods_show.html',
                  {"items": goods_brands, "active_page": 'data_show', "table_choice": table_choice})


# 客户评论表展示
def goods_customerreview_show(request):
    table_choice = request.GET.get('table_choice')
    goods_customerreviews = models.RatingGroupSummary.objects.all()
    return render(request, 'goods_show.html',
                  {"items": goods_customerreviews, "active_page": 'data_show', "table_choice": table_choice})
